package com.xiaochun.hxhj;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.myview.CountDownButton;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.RequestManager;
import com.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
//启动页一张图片3到5秒------视频页面（第一次）---首页---------（修改密码）

public class RegisterActivity extends BaseActivity implements View.OnClickListener {

    private TextView tv_login_register;
    private CountDownButton tv_getcode;
    private EditText et_mobile;
    private EditText et_code;
    private LinearLayout ll_rebackq;
    private String etmobile;
    private String etcode;
    private EditText et_pwd;
    private String etpwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    @Override
    protected void initListener() {
        ll_rebackq.setOnClickListener(this);
        tv_getcode.setOnClickListener(this);
        tv_login_register.setOnClickListener(this);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_register;
    }
    @Override
    protected void initView() {
        changeTitle("");
        showRightView(false);
        hideTitleBar();
        ll_rebackq = findViewById(R.id.ll_rebackq);
        tv_login_register = findViewById(R.id.tv_login_register);
        et_mobile = findViewById(R.id.et_mobile);
        et_code = findViewById(R.id.et_code);
        et_pwd = findViewById(R.id.et_pwd);
        tv_getcode = findViewById(R.id.tv_getcode);



    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ll_rebackq:
                finish();
                break;
            case R.id.tv_getcode:
                String phone = et_mobile.getText().toString().trim();
                if ("".equals(phone)){
                    ToastUtils.show("手机号码不能为空");
                    return;
                }
                getCode(phone);
                break;
            case R.id.tv_login_register:
                etmobile = et_mobile.getText().toString().trim();
                etcode = et_code.getText().toString().trim();
                etpwd = et_pwd.getText().toString().trim();

                if ("".equals(etmobile)){
                    ToastUtils.show("手机号码不能为空");
                    return;
                }
                if ("".equals(etpwd)){
                    ToastUtils.show("密码不能为空");
                    return;
                }
                if ("".equals(etcode)){
                    ToastUtils.show("验证码不能为空");
                    return;
                }
                login();
                break;



        }
    }

    private void getCode(String phone) {
        String url = myapp.getWebConfig() + "/api/sms/send";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("mobile", phone);
        paramsMap.put("event", "register");
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    //验证码发送成功
                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    private void login() {
        String url = myapp.getWebConfig() + "/api/user/register";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("mobile", etmobile);
        paramsMap.put("code", etcode);
        paramsMap.put("password", etpwd);
        paramsMap.put("device_id", myapp.getDeviceId());
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }



                    JSONObject data2 = jsonObject.getJSONObject("data");
                    JSONObject data = data2.getJSONObject("userinfo");
                    String user_id = data.getString("user_id");
                    String username = data.getString("username");
                    String nickname = data.getString("nickname");
                    String mobile = data.getString("mobile");
                    String avatar = data.getString("avatar");
                    String score = data.getString("score");
                    String student_id = data.getString("student_id");
                    String is_bind_wx = data.getString("is_bind_wx");
                    String token = data.getString("token");
                    String is_agent = data.getString("is_agent");
                    String vip_expire = data.getString("vip_expire");
                    String is_vip = data.getString("is_vip");
                    saveUserInfo("user_id",user_id);
                    saveUserInfo("username",username);
                    saveUserInfo("nickname",nickname);
                    saveUserInfo("mobile",mobile);
                    saveUserInfo("avatar",avatar);
                    saveUserInfo("score",score);
                    saveUserInfo("student_id",student_id);
                    saveUserInfo("is_bind_wx",is_bind_wx);
                    saveUserInfo("token",token);
                    saveUserInfo("is_agent",is_agent);
                    saveUserInfo("vip_expire",vip_expire);
                    saveUserInfo("is_vip",is_vip);

                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }


    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    String str = (String) msg.obj;
                    showToast(str);

                    break;
                case 1:
                    showToast("网络错误，请稍后重试！");
                    break;
                case 2:
                    //发送验证码成功
                    //这里判断是否倒计时结束，避免在倒计时时多次点击导致重复请求接口
                    if (tv_getcode.isFinish()) {
                        //发送验证码请求成功后调用
                        tv_getcode.start();
                    }
                    break;
                case 3:
//                    com.xiaochun.hxhj.LoginActivity

                    String isRestarApp = getUserInfo("isRestarApp");
                    if ("true".equals(isRestarApp)){
                        Intent intent = new Intent(context,MainActivity.class);
                        startActivity(intent);
                        saveUserInfo("isRestarApp","false");
                    }

                    EventBus.getDefault().post(new InfoEventMessage("登录签到"));
                    ToastUtils.show("登录成功");
                    myapp.destoryActivity("com.xiaochun.hxhj.LoginActivity");
                    myapp.destoryActivity("com.xiaochun.hxhj.LoginByMobileActivity");
                    finish();
                    break;
                case 4:

                    break;
                case 11:

                    break;
                case 12:

                    break;
            }
        }
    };

}
